﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Activity.Helper
{

    /// <summary>
    /// JSON相关操作
    /// </summary>
    public static class JsonHelper
    {
        /// <summary>
        /// JsonConvert.SerializeObject(obj)的快捷方式
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJson(this object obj)
        {
            return JsonConvert.SerializeObject(obj);
        }
        /// <summary>
        /// JsonConvert.DeserializeObject&lt;T&gt;(str)的快捷方式
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="str"></param>
        /// <returns></returns>
        public static T FromJson<T>(this string str)
        {
            return JsonConvert.DeserializeObject<T>(str);
        }

        /// <summary>
        /// JsonConvert.DeserializeObject(str,type)的快捷方式
        /// </summary>
        /// <param name="str"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static object FromJson(this string str, Type type)
        {
            return JsonConvert.DeserializeObject(str, type);
        }

        public static string GetFileJson(string filepath)
        {
            var path = System.Web.HttpContext.Current.Server.MapPath(filepath);
            string json = string.Empty;
            using (FileStream fs = new FileStream(path, FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite))
            {
                using (StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("utf-8")))
                {
                    json = sr.ReadToEnd().ToString();
                }
            }
            return json;
        }
    }
}
